﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System;

public class CopyHeroCtrl : MonoBehaviour
{
    public float bulletSpeed = 20f;
    public Rigidbody2D rocket;
    public Transform gunTransform;
    public HealthBar heal;
    public int frameIntv;

    private Animator anim;
    private AudioSource auds;
    private bool faceR = true;
    private Transform gunAnimator;
    private Vector3 lastPostion;
    private int frameCounter = 0;
    private Rigidbody2D m_Rigidbody2D;

    void Start()
    {
        m_Rigidbody2D = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        auds = GetComponent<AudioSource>();
        if (Client.isLeft)
        {
            Flip();
        }
        lastPostion = transform.position;
    }

    private void FixedUpdate()
    {
        anim.SetFloat("speed", Mathf.Abs(lastPostion.x - transform.position.x));
        if(Mathf.Abs(lastPostion.y - transform.position.y) > 0.15f)
        {
            anim.SetTrigger("Jump");
        }

        if(frameCounter < frameIntv)
        {
            frameCounter++;
        }
        else
        {
            lastPostion = transform.position;
            frameCounter = 0;
        }
    }


    public void Fire()
    {
        auds.Play();
        anim.SetTrigger("Fire");//设置过渡到射击动画的触发器
        int i = Convert.ToInt16(!faceR);
        Rigidbody2D bullet = Instantiate(rocket, gunTransform.position, Quaternion.Euler(0, 0, 180f * i));
        bullet.velocity = new Vector2(bulletSpeed * (1 - 2 * i), 0);
    }

    public void Flip()
    {
        faceR = !faceR;
        Vector3 theScale = transform.localScale;
        transform.localScale = new Vector3(theScale.x * -1, theScale.y, theScale.z);
    }

    public void Damage()
    {
        Debug.Log("copyDamage");
        if (heal.takeDamage() <= 0)
        {
            GameObject.Find("Main Camera").GetComponent<CameraFollow>().playerTrans = transform;
            m_Rigidbody2D.gravityScale = 1f;
            anim.SetTrigger("Death"); //死亡动画触发器
            Collider2D[] colliders = GetComponents<Collider2D>();
            foreach (Collider2D c in colliders) c.isTrigger = true;
            SpriteRenderer[] renderers = GetComponentsInChildren<SpriteRenderer>();
            foreach (SpriteRenderer renderer in renderers) renderer.sortingLayerName = "UI";
            GameObject.Find("Gun").GetComponent<Gun>().enabled = false;
        }
    }

    public void Fall()
    {
        m_Rigidbody2D.gravityScale = 1f;
    }
}

